package com.song.tools.core.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 异步工具类
 *
 * @author song tools
 * @since 2024-07-17
 */
public class AsyncUtil {

    /**
     * 获取异步组件
     *
     * @param executor 线程池
     * @return 异步组件
     */
    public static AsyncComponent getAsyncComponent(Executor executor) {
        return new AsyncComponent(executor);
    }


    /**
     * 异步组件
     */
    public static class AsyncComponent {

        /**
         * 线程池
         */
        private final Executor executor;

        private final List<CompletableFuture<Void>> futures;

        public AsyncComponent(Executor executor) {
            this.executor = executor;
            this.futures = new ArrayList<>();
        }

        /**
         * 增加runnable任务
         *
         * @param runnable runnable
         * @return 当前异步对象
         */
        public AsyncComponent addRunTask(Runnable runnable) {
            futures.add(CompletableFuture.runAsync(runnable, executor));
            return this;
        }

        /**
         * 执行任务
         */
        public void execute() {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        }
    }
}
